from rest_framework.views import APIView
from rest_framework.response import Response
from apps.api.models.host import hostModel
from utils.ssh import SSHParamiko


# Create your views here.
class CmdExecView(APIView):

    def post(self, request):
        host_ids = request.data.get('host_ids')
        cmd = request.data.get('cmd')
        print("host_ids: ", host_ids)

        host_object = hostModel()
        if host_ids and cmd:
            exec_host_list = host_object.get_host_by_list(host_ids)
            print(exec_host_list)

            response_list = []
            for host in exec_host_list:
                ssh = SSHParamiko(hostname=host['ip_addr'], port=host['port'], username=host['username'], pkey=None, password=host['password'])
                ssh.get_connected_client()

                # ssh 远程执行指令
                res_code, res_data = ssh.execute_cmd(cmd)
                # res_code为0表示ok，不为0说明指令执行有问题
                response_list.append({
                    'host_info': {
                        'id': host['id'],
                        'name': host['name'],
                        'ip_addr': host['ip_addr'],
                        'port': host['port'],
                    },
                    'res_code': res_code,
                    'res_data': res_data,
                })

                ssh.close()

            print(response_list)
            return Response(response_list)

        else:
            return Response({'error': '没有该主机或者没有输入指令'}, status=400)


class TemplateView(APIView):
    # 获取所有执行模板
    pass


class TemplateCategoryView(APIView):
    # 获取执行模板类别
    pass